<?php
declare (strict_types = 1);

namespace app\webadmin\controller;

use app\webadmin\BaseController;
use think\facade\Db;
use think\facade\View;
use \think\facade\Log;
use app\webadmin\validate\KefuCheck;
use think\exception\ValidateException;
use app\webadmin\model\Kefu as KefuList;

class Kefu extends BaseController
{
    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            if (!empty($param['keywords'])) {
                $where[] = ['id|name', 'like', '%' . $param['keywords'] . '%'];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $content = KefuList::where($where)
                ->order('id desc')
                ->paginate($rows, false, ['query' => $param])->each(function ($item, $k) {
                    $item['createtime'] = date('Y-m-d H:i:s', $item['create_time']);

                    return $item;
                });

            return table_assign(0, '', $content);
        } else {
            return view();
        }
    }

    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            if (!empty($param['id']) && $param['id'] > 0) {
                //修改
                try {
                    validate(KefuCheck::class)->scene('edit')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                $param['update_time'] = time();
                $res = KefuList::strict(false)->field(true)->update($param);
                if ($res) {
                    add_log('edit', $param['id'], $param);
                    return to_assign(0, "修改成功");
                }
                return to_assign();
            } else {
                //新增
                try {
                    validate(KefuCheck::class)->scene('add')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                $param['create_time'] = time();
                $insertId = KefuList::strict(false)->field(true)->insertGetId($param);
                if ($insertId) {
                    add_log('add', $insertId, $param);
                    return to_assign(0, "添加成功");
                }
                return to_assign();
            }
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $types = KefuList::where(['id' => $id])->find();
                View::assign('data', $types);
            }
            View::assign('id', $id);
            return view();
        }
    }

}